#! /usr/bin/env python
#coding=utf-8
from LinkSQL import LinkSQL, LogSQL
from MemCachePools import MemCachePools as MC
from JsonCode import JsonCode

from Ini2Dict import Ini2Dict
i = Ini2Dict()
ini = i.GetDict() 

class SwitchDB:
    
    def __init__(self):
        self.MRes = None
        self.Error = "APP_SQL_Error"
    
    def SWDoing(self, jsdb):
        
        if type(jsdb) is not dict:
            return self.Error + " for not dict"

        if "sql" in jsdb:
            if jsdb["sql"]["rw"]=="r":
                if "extime" in jsdb["sql"]:
                    if jsdb["sql"]["extime"]=='null' :
                        ext = 0
                    else:
                        ext = int(jsdb["sql"]["extime"])
                else:
                    ext = 0
                res = self.MemCache_Value(str(jsdb["sql"]["key"]), jsdb["sql"]["sub"], ext)
                              
                return res
            else:
                res = self.Dosql(jsdb["sql"]["sub"], 1)
                global ini
                if int(ini["server-id"])==1:
                    from TellOther import TellOther
                    to = TellOther()
                    to.TellSync()
                return res
                
        elif "mem" in jsdb:
            mcc = MC()
            act = jsdb["mem"]["action"]
            key = str(jsdb["mem"]["key"])
            
            if "delta" in jsdb["mem"]:
                delta = jsdb["mem"]["delta"]
            else:
                delta = 1
   
            if act == "get":
                return mcc.mGet(key)
            elif act == "del":
                mcc.mDel(key)
                return None
            elif act == "set":
                try:                    
                    mcc.mSet(key, jsdb["mem"]["val"], int(jsdb["mem"]["extime"]))
                except:
                    pass
                return None
            elif act == "dec":                
                mcc.mDec(key, delta)
                return None
            elif act == "inc":
                mcc.mInc(key, delta)
                return None
            elif act == "flush":
                mcc.mFlashAll()
                return None
            else:
                return None
            
        elif "syncing" in jsdb:
            """ client  """
            self.LoopULog()
            
        elif "sync" in jsdb:
            """ Server """
            id = jsdb["sync"]
            import time
            tn = time.strftime('%Y%U', time.localtime())
            sql = "SELECT `id`, `sql` FROM `sql_log_%s` WHERE `id` > %d LIMIT 1"%(tn, int(id) )
            db = LogSQL()
            db.SQLQuery(sql)
            res = db.GetOne()
            return res

        else:
            return 'error 2'
            
    def Dosql(self, sub, flag=0):
        sql = LinkSQL()
        mRes = ''
        if flag:
            try:
                sql.SQLQuery(sub)
                lastrowid = sql.Lastrowid()
                if lastrowid>0:
                    mRes = ({'id':lastrowid},)
                sql.Commit()                
                #sql.DBClose()
            except:
                sql = None
                from Log import Log
                l = Log()
                l.WriteEro(sub)
                return self.Error + "for sql error"

            if sql != None:
                import time, re
                tn = time.strftime('%Y%U', time.localtime())
                #print sub
                sub =  sub.encode('utf8')
                sub = re.sub(r'\'', '\\\'', sub)
                lsql = "INSERT INTO `sql_log`.`sql_log_%s` (`sql`)VALUES ('%s');"%(tn, sub)
                sql.SQLQuery(lsql)
                sql.Commit()
                sql.DBClose()
        else:
            
            sql.SQLQuery(sub)
            mRes = sql.GetAll()
            sql.DBClose()
        if len(mRes) > 0:
            return mRes
        
    def MemCache_Value(self, key, sub, extime=0):

        if extime > 0:
            mRes = self.mGet(key)
            if mRes == None:
                mRes = self.Dosql(sub)               
                self.mSet(key, mRes, extime)
        else:
            mRes = self.Dosql(sub)
        return mRes

    def mGet(self, key):
        mcc = MC()
        return mcc.mGet(key)
        
    def mSet(self, key, sub, extime=0):
        mcc = MC()
        mcc.mSet(key, sub, int(extime))

    def spid(self, sub):
        self.Dosql(sub)
    
    def jsEncode(self, val):
        js = JsonCode()
        return js.EnCode(val)
    
    def jsDECode(self, val):
        js = JsonCode()
        return js.DECode(val)    
    
    def md5_key(self, sub):
        import hashlib
        m = hashlib.md5()
        m.update(sub)
        m5 = m.hexdigest()
        return m5
    
    def LoopULog(self):
        import time
        tn = time.strftime('%Y%U', time.localtime())
        sql = "SELECT `id` FROM `sql_log_%s` ORDER BY `id` DESC LIMIT 1"%tn
        
        db = LogSQL()
        db.SQLQuery(sql)
        id = db.GetOne()
        
        if id == None:
            id = {'id': '0'}
        from TellOther import TellOther
        to = TellOther()
        to.GetSync(id)        
